<template>
  <div class="messages-container">
    <!-- 调试面板 -->
    <!-- <div v-if="DEBUG" class="debug-panel" style="margin: 10px 0; padding: 10px; border: 1px solid #ddd; background-color: #f5f5f5;">
      <h3>调试信息</h3>
      <div>当前标签: {{ activeTab }}</div>
      <div>当前页码: {{ currentPage }}</div>
      <div>总条数: {{ store?.state?.message?.total || 0 }}</div>
      <div>总页数: {{ totalPages }}</div>
      <div>Store消息数量: {{ store?.state?.message?.messages?.length || 0 }}</div>
      <div>本地消息数量: {{ messages.length }}</div>
      <div v-if="store?.state?.message?.messages?.length > 0">
        <div>Store第一条消息 (原始): {{ JSON.stringify(store?.state?.message?.messages?.[0] || {}) }}</div>
      </div>
      <div v-if="messages.length > 0">
        <div>本地第一条消息 (原始): {{ JSON.stringify(messages[0]) }}</div>
        <div>本地第一条消息 (格式化): {{ messages[0].content }}</div>
        <div>发送者: {{ messages[0].postUser?.nickname }}</div>
      </div>
      <div v-else>
        <div>消息列表为空</div>
      </div>
      <el-button @click="fetchTotalMessageCount">刷新总数</el-button>
      <el-button @click="fetchMessages">刷新消息</el-button>
      <el-button @click="dumpStoreMessages">输出Vuex Store消息</el-button>
    </div> -->

    <el-card class="messages-card">
      <template #header>
        <div class="card-header">
          <h2>站内消息</h2>
          <div class="header-actions">
            <el-button size="small" @click="markAllAsRead" :disabled="unreadCount === 0">
              标记全部已读
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="message-tabs">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="全部消息" name="all">
            <template #label>
              <span>全部消息 
                <el-badge v-if="categoryCounts.all > 0" :value="categoryCounts.all" class="tab-badge" />
              </span>
            </template>
          </el-tab-pane>
          
          <el-tab-pane label="未读消息" name="unread">
            <template #label>
              <span>未读消息 
                <el-badge v-if="categoryCounts.unread > 0" :value="categoryCounts.unread" class="tab-badge" type="danger" />
              </span>
            </template>
          </el-tab-pane>
          
          <el-tab-pane label="私信" name="private">
            <template #label>
              <span>私信 
                <el-badge v-if="categoryCounts.private > 0" :value="categoryCounts.private" class="tab-badge" />
              </span>
            </template>
          </el-tab-pane>
          
          <el-tab-pane label="系统通知" name="system">
            <template #label>
              <span>系统通知 
                <el-badge v-if="categoryCounts.system > 0" :value="categoryCounts.system" class="tab-badge" />
              </span>
            </template>
          </el-tab-pane>
          
          <el-tab-pane label="评论回复" name="comment">
            <template #label>
              <span>评论回复 
                <el-badge v-if="categoryCounts.comment > 0" :value="categoryCounts.comment" class="tab-badge" />
              </span>
            </template>
          </el-tab-pane>
          
          <el-tab-pane label="点赞提醒" name="like">
            <template #label>
              <span>点赞提醒 
                <el-badge v-if="categoryCounts.like > 0" :value="categoryCounts.like" class="tab-badge" />
              </span>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <!-- 加载中 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated :count="5" />
      </div>
      
      <!-- 暂无消息 -->
      <el-empty v-if="!loading && messages.length === 0" description="暂无消息" />
      
      <!-- 消息列表 -->
      <div v-if="!loading && normalizedMessages.length > 0" class="message-list">
        <div
          v-for="msg in normalizedMessages"
          :key="msg.id"
          class="message-item"
          :class="{ 'message-unread': !msg.hasRead }"
          @click="openReplyDialog(msg)"
        >
          <div class="message-avatar" @click.stop="goToUserProfile(msg.postUserId)">
            <img :src="msg.postUser?.avatarUrl ? (msg.postUser.avatarUrl.startsWith('http') ? msg.postUser.avatarUrl : `http://localhost:5855${msg.postUser.avatarUrl.startsWith('/') ? '' : '/'}${msg.postUser.avatarUrl}`) : (msg.postUser?.avatar ? (msg.postUser.avatar.startsWith('http') ? msg.postUser.avatar : `http://localhost:5855${msg.postUser.avatar.startsWith('/') ? '' : '/'}${msg.postUser.avatar}`) : defaultAvatar)" alt="头像" />
          </div>
          <div class="message-content">
            <div class="message-header">
              <span class="message-title">{{ msg.postUser?.nickname || '未知用户' }}</span>
              <span class="message-time">{{ formatDate(msg.createTime) }}</span>
            </div>
            <div class="message-body">{{ msg.content }}</div>
          </div>
          <div class="message-actions">
            <el-button
              size="small"
              type="danger"
              @click.stop="deleteMessage(msg.id)"
            >删除</el-button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="message-pagination">
        <el-pagination
          v-if="categoryCounts[activeTab] > 0"
          background
          layout="prev, pager, next"
          :total="categoryCounts[activeTab] || 0"
          :page-size="pageSize"
          :current-page="currentPage"
          :pager-count="5"
          @current-change="handlePageChange"
        />
      </div>
      
      <!-- 消息回复对话框 -->
      <el-dialog
        v-model="replyDialogVisible"
        title="回复消息"
        width="500px"
        destroy-on-close
        @closed="handleDialogClosed"
      >
        <div v-if="selectedMessage" class="reply-original-message">
          <div class="reply-message-header">
            <el-avatar :size="36" :src="getAvatarUrl(selectedMessage)"></el-avatar>
            <div style="margin-left: 12px; flex: 1;">
              <div style="display: flex; justify-content: space-between; margin-bottom: 6px;">
                <span class="reply-sender-name" style="font-weight: 600; font-size: 16px; color: #409EFF;">
                  {{ getSenderName(selectedMessage) }}
                </span>
                <span style="color: #909399; font-size: 13px;">
                  {{ formatDate(selectedMessage.createTime) }}
                </span>
              </div>
              <div class="reply-message-content" style="margin: 10px 0; color: #333; line-height: 1.5;">
                {{ selectedMessage.content }}
              </div>
            </div>
          </div>
        </div>
        <el-form ref="replyForm" :model="replyForm" :rules="replyRules" style="margin-top: 15px;">
          <el-form-item prop="content">
            <!-- 自定义的输入区域 -->
            <div class="custom-textarea-container">
              <textarea
                class="custom-textarea"
                v-model="replyContent"
                placeholder="请输入回复内容..."
                rows="4"
                maxlength="500"
                @input="handleInput"
                @focus="handleFocus"
              ></textarea>
              <div class="textarea-counter">{{ contentLength }}/500</div>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="replyDialogVisible = false">取消</el-button>
            <el-button type="primary" :loading="sendingReply" @click="sendReply">发送</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import api from '@/api'

export default {
  name: 'Messages',
  
  setup() {
    const store = useStore()
    
    const router = useRouter()
    const loading = ref(true)
    const messages = ref([])
    const activeTab = ref('all')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const defaultAvatar = require('@/assets/default-avatar.png')
    const messagesLoaded = ref(false) // 消息加载状态
    
    // 计算未读消息数
    const unreadCount = computed(() => store?.state?.message?.unreadCount || 0)
    
    // 计算总消息数
    const total = computed(() => store?.state?.message?.total || 0)
    
    // 计算安全的字数
    const contentLength = computed(() => {
      return (replyContent.value) ? replyContent.value.length : 0;
    })
    
    // 消息回复对话框状态
    const replyDialogVisible = ref(false)
    const selectedMessage = ref(null)
    const replyContent = ref('')
    const replyRules = ref({
      content: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
    })
    const sendingReply = ref(false)
    
    // 查询参数
    const queryParams = ref({});
    
    // 根据标签设置初始查询参数
    if (activeTab.value === 'unread') {
      queryParams.value = { status: 0 };
    }
    
    // 用于存储定时器引用
    let timer = null;
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return ''
      
      // 设置moment为中文
      moment.locale('zh-cn');
      
      const msgDate = moment(date)
      const now = moment()
      
      if (now.diff(msgDate, 'hours') < 24) {
        // 24小时内显示"xx分钟前"、"xx小时前"
        return msgDate.fromNow()
      } else if (now.diff(msgDate, 'days') < 7) {
        // 一周内显示"周几 HH:mm"
        return msgDate.format('dddd HH:mm')
      } else {
        // 超过一周显示完整日期时间
        return msgDate.format('YYYY-MM-DD HH:mm')
      }
    }
    
    // 在setup中添加计算属性
    const totalPages = computed(() => {
      // 首先使用当前标签的分类计数（如果可用）
      if (activeTab.value && categoryCounts.value[activeTab.value] !== undefined) {
        const categoryTotal = categoryCounts.value[activeTab.value];
        if (typeof categoryTotal === 'number' && categoryTotal > 0) {
          return Math.ceil(categoryTotal / pageSize.value);
        }
      }
      
      // 回退到store中的total值
      if (typeof total.value !== 'number' || total.value <= 0) return 1;
      return Math.ceil(total.value / pageSize.value);
    });
    
    // 创建请求参数
    const createRequestParams = () => {
      // 合并查询参数和分页参数
      const params = { 
        ...queryParams.value,
        page: currentPage.value,
        size: pageSize.value,
        // 添加时间戳防止缓存
        _t: new Date().getTime()
      };
      
      // 根据当前标签设置参数
      switch (activeTab.value) {
        case 'unread':
          params.status = 0; // 未读消息
          break;
        case 'private':
          params.type = 'private'; // 私信消息
          break;
        case 'system':
          params.type = 'system'; // 系统通知
          break;
        case 'comment':
          params.type = 'comment'; // 评论回复
          break;
        case 'like':
          params.type = 'like'; // 点赞提醒
          break;
        case 'all':
        default:
          // 不添加特定过滤条件，获取全部消息
          break;
      }
      
      return params;
    };
    
    // 获取消息总数
    const fetchTotalMessageCount = async () => {
      try {
        // 创建请求参数
        const requestParams = {
          ...createRequestParams(),
          count: true
        };
        
        // 调用API获取消息总数
        const response = await api.message.getList(requestParams);
        
        // 提取总数
        let count = 0;
        if (response && (response.code === 0 || response.success)) {
          if (response.data && typeof response.data.total === 'number') {
            count = response.data.total;
          } else if (typeof response.total === 'number') {
            count = response.total;
          } else if (Array.isArray(response.data)) {
            count = response.data.length;
          }
        }
        
        // 确保总数不为0，如果没有消息则显示0条
        if (count < 0) count = 0;
        
        // 更新状态
        if (store?.state?.message) {
          store.commit('message/SET_TOTAL', count);
        }
        
        return count;
      } catch (error) {
        // 设置默认值为0
        if (store?.state?.message) {
          store.commit('message/SET_TOTAL', 0);
        }
        return 0;
      }
    };
    
    // 获取消息列表
    const fetchMessages = async () => {
      if (!store) {
        return;
      }
      
      try {
        loading.value = true;
        
        // 创建请求参数
        const params = createRequestParams();
        
        // 使用正确的分页参数
        store.commit('message/SET_PARAMS', params);
        
        // 请求数据
        const result = await store.dispatch('message/getMessages', params);
        
        // 获取消息和总数
        messages.value = store.state.message?.messages || [];
        
        // 确保总数正确
        if (result && typeof result.total === 'number') {
          // 使用API返回的总数
          store.commit('message/SET_TOTAL', result.total);
        } else if (categoryCounts.value[activeTab.value] !== undefined) {
          // 如果API没有返回总数，使用分类计数
          const categoryTotal = categoryCounts.value[activeTab.value]; 
          store.commit('message/SET_TOTAL', categoryTotal);
        }
        
        // 从store获取最新总数
        total.value = store.state.message?.total || 0;
        
        // 更新已加载状态
        messagesLoaded.value = true;
      } catch (error) {
        ElMessage.error('获取消息列表失败，请重试');
      } finally {
        loading.value = false;
      }
    };
    
    // 处理标签点击事件
    const handleTabClick = async (tab) => {
      // 重置为第一页
      if (currentPage.value !== 1) {
        currentPage.value = 1;
      }
      
      // 记录当前活动标签
      activeTab.value = tab.props.name;
      
      // 更新查询参数
      updateQueryParamsByActiveTab();
      
      // 更新当前分类总数到Vuex
      if (categoryCounts.value[activeTab.value] !== undefined) {
        const currentCategoryCount = categoryCounts.value[activeTab.value];
        store.commit('message/SET_TOTAL', currentCategoryCount);
        total.value = currentCategoryCount;
      }
      
      // 清空消息列表以显示加载状态
      messages.value = [];
      loading.value = true;
      
      // 加载新数据
      await fetchMessages();
      
      // 自动标记该分类消息为已读
      if (activeTab.value !== 'all' && activeTab.value !== 'unread') {
        markCurrentTabAsRead();
      }
    };
    
    // 处理分页
    const handlePageChange = async (page) => {
      // 更新当前页码
      currentPage.value = page;
      
      // 清空消息列表以显示加载状态
      messages.value = [];
      loading.value = true;
      
      try {
        // 确保queryParams中包含了当前标签的筛选条件
        updateQueryParamsByActiveTab();
        
        // 加载当前页的消息
        await fetchMessages();
      } catch (error) {
        ElMessage.error('加载消息失败，请重试');
      } finally {
        loading.value = false;
      }
    }
    
    // 根据当前标签更新查询参数
    const updateQueryParamsByActiveTab = () => {
      // 重置查询参数
      queryParams.value = {};
      
      // 根据当前标签设置查询参数
      switch (activeTab.value) {
        case 'unread':
          queryParams.value.status = 0; // 未读消息
          break;
        case 'private':
          queryParams.value.type = 'private'; // 私信消息
          break;
        case 'system':
          queryParams.value.type = 'system'; // 系统通知
          break;
        case 'comment':
          queryParams.value.type = 'comment'; // 评论回复
          break;
        case 'like':
          queryParams.value.type = 'like'; // 点赞提醒
          break;
        case 'all':
        default:
          // 不添加特定过滤条件，获取全部消息
          break;
      }
    }
    
    // 刷新未读消息数量
    const refreshUnreadCount = async () => {
      if (!store) return;
      
      try {
        // 获取当前消息列表
        const currentMessages = store.state.message?.messages || [];
        
        // 手动计算未读消息数量 - state: 0 表示未读
        let unreadCount = 0;
        
        if (currentMessages.length > 0) {
          unreadCount = currentMessages.filter(msg => msg.state === 0).length;
        } else {
          // 如果没有本地消息，则尝试从API获取
          unreadCount = await store.dispatch('message/fetchUnreadMessageCount');
        }
        
        // 更新未读计数
        store.commit('message/SET_UNREAD_COUNT', unreadCount);
        
        // 更新分类计数
        categoryCounts.value.unread = unreadCount;
        
        return unreadCount;
      } catch (error) {
        return 0;
      }
    };
    
    // 标记消息为已读
    const markAsRead = async (id) => {
      try {
        // 先在本地更新
        const index = messages.value.findIndex(msg => msg.id === id);
        if (index !== -1) {
          // 更新本地消息状态
          messages.value[index] = {
            ...messages.value[index],
            state: 1,
            hasRead: true
          };
        }
        
        // 调用API完成标记
        const success = await store.dispatch('message/markAsRead', id);
        
        if (success) {
          // 更新未读数量
          await refreshUnreadCount();
        } else {
          // 恢复消息状态
          if (index !== -1) {
            messages.value[index] = {
              ...messages.value[index],
              state: 0,
              hasRead: false
            };
          }
        }
        
        return success;
      } catch (error) {
        return false;
      }
    };
    
    // 标记全部已读
    const markAllAsRead = async () => {
      try {
        // 先更新本地状态
        messages.value = messages.value.map(msg => ({
          ...msg,
          state: 1,
          hasRead: true
        }));
        
        // 调用API标记全部已读
        const success = await store.dispatch('message/markAllAsRead');
        
        if (success) {
          // 更新未读数量为0
          store.commit('message/SET_UNREAD_COUNT', 0);
          categoryCounts.value.unread = 0;
          
          // 刷新消息列表
          await fetchMessages();
        } else {
          // 恢复未读状态（API调用失败时）
          await fetchMessages();
        }
        
        return success;
      } catch (error) {
        return false;
      }
    };
    
    // 删除消息
    const deleteMessage = async (id) => {
      if (!id) {
        ElMessage.warning('无效的消息');
        return;
      }
      
      try {
        // 确认删除
        const result = await ElMessageBox.confirm(
          '确定要删除这条消息吗？',
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        if (result !== 'confirm') return;
        
        // 先从本地列表中移除消息（乐观更新）
        const messageIndex = messages.value.findIndex(m => m.id === id);
        if (messageIndex !== -1) {
          // 从列表中移除
          messages.value.splice(messageIndex, 1);
          
          // 如果删除的是未读消息，需要更新未读数
          const deletedMessage = messages.value[messageIndex];
          if (deletedMessage && !deletedMessage.hasRead) {
            // 更新未读数量
            refreshUnreadCount();
          }
        }
        
        // 调用真实API删除消息
        const response = await api.message.delete(id);
        
        if (response && (response.success || response.code === 0)) {
          ElMessage.success('消息已删除');
          
          // 如果当前页没有消息了，则获取新的消息列表
          if (messages.value.length === 0) {
            if (currentPage.value > 1) {
              // 如果不是第一页，回到上一页
              currentPage.value--;
            }
            // 重新加载消息
            await fetchMessages();
          }
        } else {
          ElMessage.error('删除失败: ' + (response?.message || '未知错误'));
          // 恢复本地数据，撤销乐观更新
          await fetchMessages();
        }
      } catch (error) {
        ElMessage.error('删除失败，请重试');
        // 恢复本地数据，撤销乐观更新
        await fetchMessages();
      }
    };
    
    // 打开消息
    const openMessage = (message) => {
      // 如果消息未读，标记为已读
      if (!message.hasRead) {
        markAsRead(message.id);
      }
      
      // 根据消息类型跳转到相应页面
      switch (message.type) {
        case 'comment':
          if (message.articleId) {
            router.push(`/article/${message.articleId}`);
          }
          break;
        case 'like':
          if (message.articleId) {
            router.push(`/article/${message.articleId}`);
          }
          break;
        case 'private':
          // 私信处理逻辑 - 显示回复对话框
          openReplyDialog(message);
          break;
        case 'system':
          // 系统通知不跳转
          break;
        default:
          if (message.url) {
            router.push(message.url);
          }
      }
    }
    
    // 打开回复对话框
    const openReplyDialog = async (message) => {
      // 先标记为已读，如果消息是未读状态
      if (message && (message.state === 0 || message.hasRead === false)) {
        await markAsRead(message.id);
      }
      
      // 设置选中的消息
      selectedMessage.value = message;
      
      // 显示对话框
      replyDialogVisible.value = true;
      
      // 确保回复内容为空
      replyContent.value = '';
    };
    
    // 跳转到用户主页
    const goToUserProfile = async (userId) => {
      if (!userId) {
        ElMessage.warning('无法找到该用户信息');
        return;
      }
      
      try {
        // 查找消息列表中该用户发送的消息
        const message = messages.value.find(msg => msg.postUserId === userId);
        
        // 如果找到未读消息，标记为已读
        if (message && !message.hasRead) {
          await markAsRead(message.id);
        }
        
        // 跳转到用户主页
        router.push(`/user/${userId}`);
      } catch (error) {
        // 即使出错，仍然尝试跳转
        router.push(`/user/${userId}`);
      }
    }
    
    // 发送回复
    const sendReply = async () => {
      // 验证回复内容
      if (!replyContent.value || !replyContent.value.trim()) {
        ElMessage.warning('请输入回复内容');
        return;
      }
      
      if (!selectedMessage.value || !selectedMessage.value.id) {
        ElMessage.warning('无效的消息，无法回复');
        replyDialogVisible.value = false;
        return;
      }
      
      try {
        sendingReply.value = true;
        
        // 调用API发送回复，这里使用正确的API方法
        const response = await api.message.reply(selectedMessage.value.id, replyContent.value.trim());
        
        if (response && (response.success || response.code === 0)) {
          ElMessage.success('回复已发送');
          replyDialogVisible.value = false;
          
          // 刷新消息列表
          await fetchMessages();
          
          // 更新未读消息数
          refreshUnreadCount();
        } else {
          ElMessage.error(response?.message || '发送回复失败，请稍后重试');
        }
      } catch (error) {
        // 显示具体错误信息
        const errorMsg = error?.response?.data?.message || error?.message || '发送回复失败，请稍后重试';
        ElMessage.error(errorMsg);
      } finally {
        sendingReply.value = false;
      }
    };
    
    // 监听未读消息数变化
    watch(() => unreadCount.value, (newCount) => {
      if (newCount === 0 && activeTab.value === 'unread') {
        // 如果当前在"未读消息"选项卡，且未读消息为0，则刷新列表
        fetchMessages();
      }
    });
    
    // 处理输入事件
    const handleInput = (event) => {
      try {
        // 获取输入内容
        const value = event && event.target ? event.target.value : '';
        
        // 直接更新replyContent
        replyContent.value = value;
        
        // 截断超过最大长度的文本
        if (value.length > 500) {
          replyContent.value = value.slice(0, 500);
          if (event && event.target) {
            event.target.value = replyContent.value;
          }
        }
      } catch (error) {
        // Error handled silently
      }
    }
    
    // 添加获取焦点事件处理
    const handleFocus = (event) => {
      // 确保输入框正常工作
      setTimeout(() => {
        if (event && event.target) {
          event.target.focus();
        }
      }, 100);
    }
    
    // 获取消息类型显示文本
    const getMessageTypeText = (type) => {
      switch (type) {
        case 'private': return '私信消息';
        case 'comment': return '评论回复';
        case 'like': return '点赞提醒';
        case 'system': return '系统通知';
        default: return type || '未知类型';
      }
    };
    
    // 获取发送者名称
    const getSenderName = (message) => {
      if (message.postUser && message.postUser.nickname) {
        return message.postUser.nickname;
      }
      if (message.data && message.data.postUser && message.data.postUser.nickname) {
        return message.data.postUser.nickname;
      }
      return '未知用户';
    };
    
    // 获取头像URL
    const getAvatarUrl = (message) => {
      let avatarUrl = null;
      
      if (message.postUser && message.postUser.avatarUrl) {
        avatarUrl = message.postUser.avatarUrl;
      } else if (message.data && message.data.postUser && message.data.postUser.avatarUrl) {
        avatarUrl = message.data.postUser.avatarUrl;
      }
      
      if (avatarUrl) {
        // 处理URL格式
        return avatarUrl.startsWith('http') 
          ? avatarUrl 
          : `http://localhost:5855${avatarUrl.startsWith('/') ? '' : '/'}${avatarUrl}`;
      }
      
      return defaultAvatar;
    };
    
    // 标准化消息数据
    const normalizedMessages = computed(() => {
      if (!messages.value || messages.value.length === 0) {
        return [];
      }
      
      try {
        return messages.value.map(msg => {
          // 确保所有必要的字段都存在
          const messageObj = {
            ...msg,
            id: msg.id,
            content: msg.content || '',
            postUserId: msg.postUserId,
            receiveUserId: msg.receiveUserId,
            // 确保发送者信息
            postUser: msg.postUser || { 
              nickname: msg.postUserNickname || '未知用户',
              avatar: msg.postUserAvatar || null,
              avatarUrl: msg.postUserAvatarUrl || msg.postUserAvatar || null
            },
            // 统一type字段
            type: msg.type || 'private',
            // 统一状态字段
            state: msg.state !== undefined ? msg.state : 0,
            // 统一已读状态字段
            hasRead: msg.hasRead === true || msg.state === 1,
            // 确保时间字段
            createTime: msg.createTime || new Date().toISOString(),
            updateTime: msg.updateTime || msg.createTime || new Date().toISOString()
          };

          return messageObj;
        });
      } catch (error) {
        return [];
      }
    });
    
    // 初始化时先调用一次API获取真实总数
    const initTotalCount = async () => {
      try {
        // 不需要分页参数，只获取计数
        const countParams = { count: true };
        
        // 直接调用API获取总数
        const response = await api.message.getList(countParams);
        
        // 提取总数
        let actualTotal = 0;
        
        if (response && (response.code === 0 || response.success)) {
          if (response.data && typeof response.data.total === 'number') {
            actualTotal = response.data.total;
          } else if (typeof response.total === 'number') {
            actualTotal = response.total;
          } else if (Array.isArray(response.data)) {
            // 如果返回所有数据，则列表长度就是总数
            actualTotal = response.data.length;
          }
        }
        
        // 更新store中的总数
        if (store && actualTotal > 0) {
          store.commit('message/SET_TOTAL', actualTotal);
          total.value = actualTotal;
        }
        
        return actualTotal;
      } catch (error) {
        return 0;
      }
    };
    
    // 声明一个分类计数的状态
    const categoryCounts = ref({
      all: 0,
      unread: 0,
      private: 0,
      system: 0,
      comment: 0,
      like: 0
    })
    
    // 从store获取分类计数
    const fetchCategoryCounts = async () => {
      try {
        if (!store) {
          return
        }
        
        // 调用store方法获取分类计数
        const counts = await store.dispatch('message/getCategoryCounts')
        
        if (counts && typeof counts === 'object') {
          // 更新本地状态
          categoryCounts.value = {
            ...categoryCounts.value,
            ...counts
          }
          
          // 确保all是各分类之和，如果后端没有直接返回
          if (typeof counts.all !== 'number') {
            let total = 0
            Object.keys(counts).forEach(key => {
              if (key !== 'all' && typeof counts[key] === 'number') {
                total += counts[key]
              }
            })
            categoryCounts.value.all = total
          }
          
          // 初始化时根据当前活动标签更新total
          if (activeTab.value && categoryCounts.value[activeTab.value] !== undefined) {
            const currentCategoryCount = categoryCounts.value[activeTab.value];
            store.commit('message/SET_TOTAL', currentCategoryCount);
            total.value = currentCategoryCount;
          }
        }
      } catch (error) {
        // Error handled silently
      }
    }
    
    // 计算每个分类的页数
    const categoryPages = computed(() => {
      const pages = {}
      
      Object.keys(categoryCounts.value).forEach(key => {
        const count = categoryCounts.value[key] || 0
        pages[key] = Math.max(1, Math.ceil(count / pageSize.value))
      })
      
      return pages
    })
    
    // 在页面加载完成后调用
    onMounted(async () => {
      // 添加短暂延迟，确保Vuex store完全初始化
      setTimeout(async () => {
        if (!store?.state?.message) {
          ElMessage.error('加载消息失败，请刷新页面重试')
          return
        }
        
        // 获取消息分类计数
        await fetchCategoryCounts()
        
        // 获取真实总数
        await initTotalCount()
        
        // 确保根据当前活动标签设置查询参数
        updateQueryParamsByActiveTab()
        
        // 获取消息列表
        await fetchMessages()
        
        // 最终确认一次分页信息
        if (activeTab.value && categoryCounts.value[activeTab.value]) {
          // 如果当前标签有计数，使用该计数作为总数
          const count = categoryCounts.value[activeTab.value];
          if (count > 0) {
            store.commit('message/SET_TOTAL', count);
            total.value = count;
          }
        }
        
        // 刷新未读消息数
        await refreshUnreadCount()
        
        // 设置定时刷新未读消息数
        timer = setInterval(() => {
          refreshUnreadCount()
        }, 60000) // 每分钟刷新一次
      }, 100) // 短暂延迟100ms确保初始化
    })
    
    // 在组件销毁时清除定时器
    onUnmounted(() => {
      if (timer) {
        clearInterval(timer)
        timer = null
      }
    })
    
    // 添加关闭对话框事件处理函数
    const handleDialogClosed = () => {
      // 重置回复内容
      replyContent.value = '';
      // 清空选中的消息
      selectedMessage.value = null;
    };
    
    // 标记当前标签下的所有消息为已读
    const markCurrentTabAsRead = async () => {
      try {
        if (!activeTab.value || activeTab.value === 'all' || activeTab.value === 'unread') {
          return;
        }
        
        // 准备请求参数，仅标记当前分类
        const markParams = {
          type: activeTab.value
        };
        
        // 调用接口标记为已读
        const response = await api.message.markRead(markParams);
        
        if (response && (response.code === 0 || response.success)) {
          // 刷新标记后的分类计数和未读数
          await fetchCategoryCounts();
          await refreshUnreadCount();
        }
      } catch (error) {
        // Error handled silently
      }
    };
    
    return {
      loading,
      messages,
      activeTab,
      currentPage,
      pageSize,
      total,
      unreadCount,
      defaultAvatar,
      messagesLoaded,
      formatDate,
      handleTabClick,
      handlePageChange,
      markAsRead,
      markAllAsRead,
      deleteMessage,
      openMessage,
      replyDialogVisible,
      selectedMessage,
      replyContent,
      replyRules,
      sendingReply,
      openReplyDialog,
      sendReply,
      goToUserProfile,
      handleInput,
      handleFocus,
      contentLength,
      totalPages,
      getMessageTypeText,
      getSenderName,
      getAvatarUrl,
      normalizedMessages,
      handleDialogClosed,
      categoryCounts,
      fetchCategoryCounts,
      categoryPages,
      markCurrentTabAsRead,
      fetchTotalMessageCount,
      updateQueryParamsByActiveTab
    }
  }
}
</script>

<style scoped>
.messages-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.messages-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.loading-container {
  padding: 20px 0;
}

.message-list {
  margin-top: 20px;
}

.message-item {
  display: flex;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.3s;
  cursor: pointer;
}

.message-item:hover {
  background-color: #f0f7ff;
}

.message-unread {
  background-color: #f0f9eb;
}

.message-avatar {
  margin-right: 16px;
  width: 50px;
  min-width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  transition: transform 0.2s;
}

.message-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
}

.message-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.message-content {
  flex: 1;
  overflow: hidden;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.message-title {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.message-time {
  color: #909399;
  font-size: 13px;
}

.message-sender {
  color: #409EFF;
  font-size: 14px;
  margin-bottom: 8px;
}

.message-body {
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.message-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: 16px;
}

.message-pagination {
  margin-top: 20px;
  text-align: center;
}

/* 回复对话框样式 */
.reply-original-message {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
}

.reply-message-header {
  display: flex;
  align-items: flex-start;
}

.reply-sender-name {
  margin-left: 8px;
  font-weight: 600;
}

.reply-message-content {
  color: #606266;
  padding: 8px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 修复对话框内的输入框样式 */
.el-textarea__inner {
  resize: none !important;
  min-height: 120px !important;
  padding: 12px !important;
  font-size: 15px !important;
  line-height: 1.6 !important;
  border-color: #dcdfe6 !important;
}

.el-textarea__inner:focus {
  border-color: #409EFF !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
}

@media screen and (max-width: 768px) {
  .messages-container {
    padding: 10px;
  }
  
  .message-item {
    flex-direction: column;
  }
  
  .message-avatar {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .message-actions {
    margin-left: 0;
    margin-top: 10px;
    justify-content: flex-end;
  }
}

/* 自定义文本框样式 */
.custom-textarea-container {
  position: relative;
  width: 100%;
}

.custom-textarea {
  width: 100%;
  min-height: 120px;
  padding: 12px;
  font-size: 15px;
  line-height: 1.6;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  resize: none;
  outline: none;
  transition: border-color 0.2s, box-shadow 0.2s;
  font-family: inherit;
}

.custom-textarea:focus {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.textarea-counter {
  position: absolute;
  bottom: 8px;
  right: 10px;
  font-size: 12px;
  color: #909399;
}

/* 调试信息样式 */
.pagination-debug-info {
  margin-bottom: 10px;
  padding: 5px 10px;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
  color: #67c23a;
  font-size: 12px;
}

/* 对话框样式 */
.custom-textarea-container {
  position: relative;
  width: 100%;
}

.message-list-empty {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

/* 标签徽章样式 */
.tab-badge {
  margin-left: 4px;
}

/* 页数显示样式 */
.page-count {
  margin-left: 4px;
  color: #909399;
  font-size: 12px;
  font-weight: normal;
}
</style> 